package com.zcf.gameController.gameUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zcf.gameController.F_Websocket_s;
import com.zcf.gameController.WebSocketBull;
import com.zcf.pojo.ClubUser;
import com.zcf.pojo.Msg;
import com.zcf.pojo.PlayBack;
import com.zcf.pojo.RoomRecord;
import com.zcf.pojo.RoomsParam;
import com.zcf.pojo.UserBean;

public class Util_Room {
		/**
		 * 玩家退出
		 * @param myRoom
		 * @param user
		 * @return
		 */

	public  void exitGame(RoomsParam myRoom, UserBean user , WebSocketBull ws) throws Exception {

		Map<String, Object> data = new HashMap<String, Object>();
		Msg msgs = null;

		//房间没有开始

		if (myRoom==null){
			data.clear();
			data.put("userid",user.getId());
			msgs = new Msg(300,"没在房间！",data,"exitGame");
			ws.broadcastMe(msgs,user.getSession(), user);
			return;
		}
		if(myRoom.getIsStart() <1){
			if(user.getType() != 3){
				myRoom.getLock().lock();
				try{
					if (myRoom.getPostions().contains(user.getId().intValue())){
						int i1 = myRoom.getPostions().indexOf(user.getId().intValue());
						myRoom.getPostions().set(i1,0);
					}
					user.setPosition(-1);
					user.setIsReady(0);
					user.setType(0);
				}catch (Exception e){
					e.printStackTrace();
				}finally {
					myRoom.getLock().unlock();
				}
				data.clear();
				data.put("userid",user.getId());
				data.put("positions",myRoom.getPostions());
				msgs = new Msg(200,"玩家"+user.getWxname()+"退出",data,"exitGame");
				ws.broadcastB(msgs,user.getSession().getId(),myRoom);
				data.clear();
				data.put("userid",user.getId());
				msgs = new Msg(200,"退出成功",data,"exitGame");
				ws.broadcastMe(msgs,user.getSession(), user);
				myRoom.getUsers().remove(user.getId()+"");
			}else{
				data.clear();
				data.put("userid",user.getId());
				msgs = new Msg(200,"退出成功",data,"exitGame");
				ws.broadcastMe(msgs,user.getSession(), user);

			}
		}else{
			if(user.getType() == 0){
				data.clear();
				data.put("userid",user.getId());
				msgs = new Msg(200,"退出成功",data,"exitGame");
				ws.broadcastMe(msgs,user.getSession(), user);
			}else {
				data.clear();
				data.put("userid",user.getId());
				msgs = new Msg(200,"退出成功",data,"exitGame");
				ws.broadcastMe(msgs,user.getSession(), user);
				data.clear();
				data.put("userid",user.getId());
				data.put("positions",myRoom.getPostions());
				msgs = new Msg(200,"退出成功，开启托管模式",data,"exitGame");
				ws.broadcastB(msgs,user.getSession().getId(), myRoom);
			}
			user.setType(3);
		}
	}
	/**
	 * 玩家退出
	 * @param myRoom
	 * @param user
	 * @return
	 */
	public  void exitGame(RoomsParam myRoom, UserBean user , F_Websocket_s ws) throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		Msg msgs = null;
		//房间没有开始
		if (myRoom==null){
			data.clear();
			data.put("userid",user.getId());
			msgs = new Msg(300,"没在房间！",data,"exitGame");
			ws.broadcastMe(msgs,user.getSession(), user);
			return;
		}
		if(myRoom.getIsStart() <1){
			if(user.getType() != 3){
				myRoom.getLock().lock();
				try{
					if (myRoom.getPostions().contains(user.getId().intValue())){
						int i1 = myRoom.getPostions().indexOf(user.getId().intValue());
						myRoom.getPostions().set(i1,0);
					}
					user.setPosition(-1);
					user.setIsReady(0);
					user.setType(0);
				}catch (Exception e){
					e.printStackTrace();
				}finally {
					myRoom.getLock().unlock();
				}
				data.clear();
				data.put("userid",user.getId());
				data.put("positions",myRoom.getPostions());
				msgs = new Msg(200,"玩家"+user.getWxname()+"退出",data,"exitGame");
				ws.broadcastB(msgs,user.getSession().getId(),myRoom);
				data.clear();
				data.put("userid",user.getId());
				msgs = new Msg(200,"退出成功",data,"exitGame");
				ws.broadcastMe(msgs,user.getSession(), user);
			}else{
				data.clear();
				data.put("userid",user.getId());
				msgs = new Msg(200,"退出成功",data,"exitGame");
				ws.broadcastMe(msgs,user.getSession(), user);
			}
			myRoom.getUsers().remove(user.getId()+"");
		}else{
			if(user.getType() == 0){
				data.clear();
				data.put("userid",user.getId());
				msgs = new Msg(200,"退出成功",data,"exitGame");
				ws.broadcastMe(msgs,user.getSession(), user);
			}else {
				data.clear();
				data.put("userid",user.getId());
				msgs = new Msg(200,"退出成功",data,"exitGame");
				ws.broadcastMe(msgs,user.getSession(), user);
				data.clear();
				data.put("userid",user.getId());
				data.put("positions",myRoom.getPostions());
				msgs = new Msg(200,"退出成功，开启托管模式",data,"exitGame");
				ws.broadcastB(msgs,user.getSession().getId(), myRoom);
			}
			user.setType(3);
		}
	}
	/**
	 * 玩家退出
	 * @param myRoom
	 * @param user
	 * @return
	 */

	public  void exitGame(RoomsParam myRoom, UserBean user ) throws Exception {

		Map<String, Object> data = new HashMap<String, Object>();
		Msg msgs = null;
		//房间没有开始
		if (myRoom==null){
			return;
		}
		if(myRoom.getIsStart() <1){
			if(user.getType() != 3){
				myRoom.getLock().lock();
				try{
					if (myRoom.getPostions().contains(user.getId().intValue())){
						int i1 = myRoom.getPostions().indexOf(user.getId().intValue());
						myRoom.getPostions().set(i1,0);
					}
					user.setPosition(-1);
					user.setIsReady(0);
					user.setType(3);
				}catch (Exception e){
					e.printStackTrace();
				}finally {
					myRoom.getLock().unlock();
				}
			}
		}else{
			user.setType(3);
		}
	}
	/**
	 * 准备
	 * @param myRoom
	 * @param user
	 * @return
	 */
	public Msg getPrepare(RoomsParam myRoom,UserBean user){
		Msg msgs = null;

		if(myRoom.getRoomType().get("roomType") == 1){
			ClubUser clubUser = new ClubUser().selectOne(new EntityWrapper<ClubUser>().eq("clubid", myRoom.getRoomType().get("clubid")).eq("userid", user.getId()));
			if(clubUser.getState() == 4){
				msgs = new Msg(198,"用户已被冻结",null,"prepare");
			}
		}
		return msgs;

	}

	/**
	 * 发牌
	 * @param myRoom
	 */



	/**
	 * 0 查询参与游戏的人 1 并且没有弃牌的
	 * @param myRoom
	 * @return
	 */
	public static List<UserBean> returnGameUser(RoomsParam myRoom,int type){
		List<UserBean> list = new ArrayList<UserBean>();
		if(type == 0){
			for (UserBean user : myRoom.getUsers().values()) {
				if(user.getType() == 1 || user.getType() == 2){
					list.add(user);
				}
			}
		}else if(type == 1){
			for (UserBean user : myRoom.getUsers().values()) {
				if(user.getOpentionType() !=2 && (user.getType() == 1 || user.getType() == 2)  ){
					list.add(user);
				}
			}
		}

		return list;

	}

	/**
	 * 获取下一个操作者
	 * @param param
	 * @param userid
	 */
	public int nextuser(RoomsParam param ,long userid,int type,PlayBack back){
		Integer[] postion = null;
		if(type == 0){
			postion = getGameUser(param,param.getRoomType().get("personnum"));
			for (int i = 0; i < postion.length; i++) {
				if(String.valueOf(postion[i]).equals(String.valueOf(userid))){
					if(i+1 <postion.length){
						param.setOperation_userid(postion[i+1]);
					}else{
						param.setOperation_userid(postion[0]);
					}
				}
			}
		}else if(type == 1){
			postion = getGameUsers(param,param.getRoomType().get("personnum"));
			for (int i = 0; i < postion.length; i++) {
				if(String.valueOf(postion[i]).equals(String.valueOf(userid))){
					for (int j = i; j < postion.length; j++) {
						if(j+1 <postion.length){
							if(postion[j+1]!=0 && param.getUsers().get(postion[j+1]+"").getOpentionType()!=2){
								param.setOperation_userid(postion[j+1]);
								break;
							}else{
								continue;
							}
						}else{
							j=-2;
						}
					}
				}
			}
			
			
		}
		

		UserBean bean = param.getUsers().get(String.valueOf(param.getOperation_userid()));
		System.out.println("用户操作状态"+bean.getOpentionType());
		//param.getTime_user_f().setUser(bean,back);

		return param.getOperation_userid();
	}
	/**
	 * 获取游戏中没有弃牌的人的位置
	 * @param room
	 * @param num
	 * @return
	 */
	public static Integer[] getGameUser(RoomsParam room,int num){
		Map<String, UserBean> users = room.getUsers();
		List<Integer> list = new ArrayList<Integer>();
		Integer[]arr = new Integer[num];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = 0;
		}
		Iterator<Map.Entry<String, UserBean>> iterator = users.entrySet().iterator();
		while(iterator.hasNext()){//迭代器
			Map.Entry<String, UserBean> has = iterator.next();//获取参战用户 并且 没有弃牌
			if((has.getValue().getType()==1 || has.getValue().getType() == 2) && room.getUsers().get(has.getValue().getId()+"").getOpentionType()!=2){
				/*if(has.getValue().getPosition()!=null){
					arr[has.getValue().getPosition()-1] = Integer.valueOf(String.valueOf(has.getValue().getId()));
				}*/
			}
		}
		for (int i = 0; i < arr.length; i++) {
			if(arr[i]!=0){
				list.add(arr[i]);
			}
		}//返回参战的人的位置
		Integer [] array = new Integer[list.size()];
		Integer[] array2 = list.toArray(array);
		return array2;
	}

	
	
	
	/**
	 * 获取游戏中没有弃牌的人的位置
	 * @param room
	 * @param num
	 * @return
	 */
	public static Integer[] getGameUsers(RoomsParam room,int num){
		Map<String, UserBean> users = room.getUsers();
		List<Integer> list = new ArrayList<Integer>();
		Integer[]arr = new Integer[num];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = 0;
		}
		for (UserBean user : room.getUsers().values()) {
		/*	if((user.getType() == 1 || user.getType() == 2) && user.getPosition()!=null){
				arr[user.getPosition()-1] = Integer.valueOf(String.valueOf(user.getId()));
			}*/
		}
		for (int i = 0; i < arr.length; i++) {
			if(arr[i]!=0){
				list.add(arr[i]);
			}
		}//返回参战的人的位置
		Integer [] array = new Integer[list.size()];
		Integer[] array2 = list.toArray(array);
		return array2;
	}
	
	
	
	
	
	
	/**
	 * 判断是否进入新一轮或系统自动开牌
	 * @param userBean
	 * @return
	 */
	public int NewGame(UserBean userBean,RoomsParam myRoom){
		//判断所有用户都已经操作
		int brandstatus = 0;//假设所有人都已经下注
		for(UserBean user:returnGameUser(myRoom,1)){
			//0是未操作状态1下注
			if(myRoom.getUsers().get(user.getId()+"").getOpentionType()==0){
				brandstatus++;//代表不可结算
			}
		}
		//判断当前是否为最后一轮且所有人都已经下注1
		if(myRoom.getNumber_rounds()==myRoom.getRoomType().get("subsection")&&brandstatus==0){
			//系统开牌结算
			return OpenBrand(myRoom);
		}else if(getGameUser(myRoom, myRoom.getRoomType().get("personnum")).length == 1){//获取游戏中没有弃牌的人的位置
			//直接胜利
			int state = EndGame(returnGameUser(myRoom, 1).get(0).getId().intValue(), myRoom); 
			return state;
		}else if(brandstatus==0){
			//增加轮数
			myRoom.setNumber_rounds(myRoom.getNumber_rounds()+1);
			for(UserBean user:returnGameUser(myRoom,1)){
				//初始化用户操作状态
				user.setOpentionType(0);
			}
			//return -2;
		}
		return -1;
	}

	/**
	 * 开牌比点
	 * @return
	 */
	public int OpenBrand(RoomsParam myRoom){
		//筛选出最大牌型的用户
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		Map<String, Object> map;
		/*for (UserBean user : returnGameUser(myRoom, 1)) {//把没有弃牌的用户和牌型放到map
			map = new HashMap<String, Object>();
			map.put(user.getId()+"",CardType_F.getCardType(user.getUserCards(),myRoom));
			list.add(map);
		}*/
		for (int i = 0; i < list.size(); i++) {//对集合进行降序
			Collections.sort( list ,new Comparator<Map<String, Object>>() {
				@Override
				public int compare(Map<String, Object> o1, Map<String, Object> o2) {
					int io1 =(int) o1.get(o1.keySet().toArray()[0]);
					int io2 = (int) o2.get(o2.keySet().toArray()[0]);
					return io2-io1;
				}
			});
		}
		int num = 0;
		for (int i = 0; i < list.size(); i++) {
			if(i+1 <list.size()){//看看是否有相同牌型
				if(String.valueOf(list.get(0).values().toArray()[0]).equals(String.valueOf(list.get(i+1).values().toArray()[0]))){
					num++;
				}
			}
		}
		String userid = maxcard(num, list, myRoom);//获取牌型最大的用户
		return EndGame(Integer.parseInt(userid),myRoom);


		//		//豹子牌型数量
		//		int count_baozi=0;
		//		//特殊牌型数量
		//		int count_235=0;
		//		//其他牌型数量
		//		int count=0;
		//		//用户牌值记录
		//		List<UserBean> userlist = returnGameUser(myRoom, 1);
		//		Object[] brands = new Object[userlist.size()];
		//		//获取所有用户得牌值
		//		for(int i=0;i<userlist.size();i++){
		//			int user_brand = userlist.get(i).getCardType();
		//			//特殊牌型235
		//			if(user_brand==999)count_235++;
		//			//豹子
		//			if(user_brand<999&&user_brand>899)count_baozi++;
		//			//其他牌型
		//			if(user_brand<900)count++;
		//			//记录用户id和牌型值
		//			brands[i]=new int[]{userlist.get(i).getId().intValue(),user_brand};
		//		}
		//		//和局判断如果235和豹子和其他牌型只有1个得情况下和局
		//		if(count_baozi==1&&count_235==1&&count==1){
		//			return draw(myRoom, brands);
		//		}else{
		//			//冒泡
		//			order(brands);
		//			//检测是否有相同牌型
		//			int brandcount=isBrands(brands);
		//			//有牌值相同的重新比牌
		//			if(brandcount>0&&((int[])brands[0])[1]<100){
		//				pkBrands(brandcount, myRoom, brands,1);
		//				//冒泡
		//				order(brands);
		//				//检测是否有相同牌型
		//				brandcount=isBrands(brands);
		//			}
		//			//有牌值相同的重新比牌
		//			if(brandcount>0&&((int[])brands[0])[1]<100){
		//				pkBrands(brandcount, myRoom, brands,0);
		//				//冒泡
		//				order(brands);
		//				//检测是否有相同牌型
		//				brandcount=isBrands(brands);
		//			}
		//			//和局
		//			if(brandcount>0){
		//				Object[] brandsdraw = new Object[brandcount+1];
		//				for(int i=0;i<=brandcount;i++){
		//					brandsdraw[i]=brands[i];
		//				}
		//				return draw(myRoom, brandsdraw);
		//			}
		//			//将所有底注奖励给最大值玩家
		//			return EndGame(((int[])brands[0])[0],myRoom);
		//		}
	}

	/***
	 * 和局
	 * @param pkBean
	 * @param brands
	 * @return
	 */
	//	private int draw(RoomsParam myRoom,Object[] brands){
	//		//和局逻辑
	//		int bet_count = myRoom.getDownpool();
	//		for(int i=0;i<brands.length;i++){
	//			int[] brnad_user = (int[]) brands[i]; 
	//			String state=gameDao.UpdateUserMoney(brnad_user[0], bet_count/brands.length, 1);
	//			if(!state.equals("success")){
	//				return 999;
	//			}
	//		}
	//		return 201;//和局
	//	}
	//排序
	//	private void order(Object[] brands){
	//		//冒泡排序
	//		for(int i=0;i<brands.length;i++){
	//			int[] brnad_user = (int[]) brands[i]; 
	//			for(int j=i;j<brands.length;j++){
	//				if((j+1)<brands.length){
	//					int[] brand = (int[]) brands[j+1];
	//					if(brnad_user[1]<brand[1]){
	//						brands[i]=brands[j+1];
	//						brands[j+1]=brnad_user;
	//					}
	//				}
	//			}
	//		}
	//	}
	//检测相同
	//	private int isBrands(Object[] brands){
	//		int brandcount=0;
	//		//判断是否有牌值相同
	//		for(int i=0;i<brands.length;i++){
	//			int[] brnad_user = (int[]) brands[i]; 
	//			if((i+1)<brands.length){
	//				int[] brnad_user2 = (int[]) brands[i+1]; 
	//				if(brnad_user[1]==brnad_user2[1]){
	//					brandcount++;
	//				}else{
	//					break;
	//				}
	//			}
	//		}
	//		return brandcount;
	//	}
	//比牌
	//	private void pkBrands(int brandcount,RoomsParam myRoom,Object[] brands,int number){
	//		for(int i=0;i<=brandcount;i++){
	//			UserBean userBean = myRoom.getUserBean(((int[])brands[i])[0]);
	//			int user_brand = userBean.BrandCount(number);
	//			//记录用户id和牌型值
	//			brands[i]=new int[]{userBean.getId().intValue(),user_brand};
	//		}
	//	}
	/**
	 * 结算
	 * @param userid
	 * @return
	 */
	public int EndGame(int userid,RoomsParam myRoom){
		myRoom.setWinner(userid);
		//检测总注数是否触发抽水如果触发则扣除抽水比
		//			if(myRoom.getBottom_pan()>=F_PublicState.deduct_max){
		//				//扣除抽水比
		//				myRoom.setBottom_pan(pkBean.getBottom_pan()-(pkBean.getBottom_pan()*F_PublicState.deduct)/100);
		//				System.out.println("执行抽水");
		//			}
		//将锅底及自己的注数全部奖励给总分最大的玩家
		//			String state = gameDao.UpdateUserMoney(userid, myRoom.getDownpool(), 1);
		//			if(state.equals("success")){

	/*	//检测该用户是否收喜钱
	//	int odd = CardType_F.backPatterns(myRoom.getUsers().get(userid+"").getUserCards(),myRoom);
		System.out.println("喜钱"+odd);
		//更新用户金币
		for(UserBean userBean:returnGameUser(myRoom, 0)){
			System.out.println("用户的钱"+userBean.getMoney()+"房间底分"+myRoom.getDownpool());
			if(userid==userBean.getId()){
				userBean.setWinNumber(myRoom.getDownpool()+userBean.getWinNumber());
				userBean.setMoney(userBean.getMoney()+myRoom.getDownpool()+odd*(returnGameUser(myRoom, 0).size()-1));//喜钱是除自己每个参战的用户都要
			}else{
				userBean.setMoney(userBean.getMoney()-odd);//去掉喜钱
			}
			//userBean.setBets(0);
		}*/
		//锅底清空
		//		myRoom.setDownpool(0);
		//更改房间状态
		myRoom.setIsStart(0);
		return 0;
		//			}
		//			return 999;//异常
	}
	/**
	 * 获取牌型最大的用户
	 * @param num
	 * @param list
	 * @param myRoom
	 * @return
	 */
	public String maxcard(int num,List<Map<String, Object>> list,RoomsParam myRoom){
		String userid = null ;
		if(num!=0){
		/*	for (int i = 0; i <= num; i++) {//遍历相同牌型获取最大的那个
				if(i+1<=num){
					if(i==0){
						userid = CardType_F.PkCard(myRoom.getUsers().get(String.valueOf(list.get(i).keySet().toArray()[0])).getUserCards(), myRoom.getUsers().get(String.valueOf(list.get(i+1).keySet().toArray()[0])).getUserCards(),myRoom)
								?String.valueOf(list.get(i).keySet().toArray()[0]):String.valueOf(list.get(i+1).keySet().toArray()[0]);
					}else{
						userid = CardType_F.PkCard(myRoom.getUsers().get(userid).getUserCards(), myRoom.getUsers().get(String.valueOf(list.get(i+1).keySet().toArray()[0])).getUserCards(),myRoom)
								?userid:String.valueOf(list.get(i+1).keySet().toArray()[0]);
					}
				}
			}*/
		}else{
			userid = String.valueOf(list.get(0).keySet().toArray()[0]);
		}
		return userid;
	}

	/**
	 * 比牌
	 * @param userid
	 * @param pkuserid
	 * @param myRoom
	 * @return
	 */
	public int PKUser(Long userid, int pkuserid, RoomsParam myRoom){
		/*//int usercount = CardType_F.getCardType(myRoom.getUsers().get(userid+"").getUserCards(),myRoom );
		int pkusercount = CardType_F.getCardType(myRoom.getUsers().get(pkuserid+"").getUserCards(),myRoom);
		if(Arrays.asList(myRoom.getHoptions()).contains("1")){
			if(17<=usercount&&usercount >=20&& 920<=pkusercount && pkusercount<=980){//如果自己是235 对面是豹子 自己赢
				myRoom.getUsers().get(pkuserid+"").setOpentionType(2);
			}else if(17<=pkusercount&&pkusercount >=20&& 920<=usercount && usercount<=980){//如果自己是豹子 对面是235 对面赢
				myRoom.getUsers().get(userid+"").setOpentionType(2);
			}
		}
		//获取赢的人id
		int winuserid = (int) (CardType_F.PkCard(myRoom.getUsers().get(userid+"").getUserCards(),myRoom.getUsers().get(pkuserid+"").getUserCards(),myRoom)?userid: pkuserid);
		if(pkuserid == winuserid){//输的人不能参与游戏
			myRoom.getUsers().get(userid+"").setOpentionType(2);
		}else{
			myRoom.getUsers().get(pkuserid+"").setOpentionType(2);
		}

		return winuserid;*/
	return 1;
	}
	/**
	 * 插入战绩
	 * @param myRoom
	 */
	public void insertrecord(RoomsParam myRoom) {
		RoomRecord ri = new RoomRecord();
		StringBuilder sb = new StringBuilder();
		for (UserBean ub :returnGameUser(myRoom, 0)) {

			sb.setLength(0);
			for (int i = 0; i < ub.getUserCards().size(); i++) {
				sb.append(ub.getUserCards().get(i));
				sb.append(",");
			}

			ri.setUserCards(sb.toString());//用户的牌
			ri.setRoomNum(myRoom.getRoomName());//房间号
			ri.setGameId(myRoom.getGameId());//当前局数
			ri.setPoints(myRoom.getRoomType().get("points"));//房间底分
			ri.setUid(ub.getId());//用户id
			ri.setMoney(ub.getMoney());//用户的钱
			ri.setNum(myRoom.getRoomType().get("num"));
			ri.setPhone(ub.getPhone());
			ri.setUsername(ub.getWxname());
			ri.setUserimg(ub.getWximg());
			//ri.setCardType(CardType_F.getCardType(ub.getUserCards(),myRoom));//用户牌型
			ri.setRoomType(myRoom.getRoomType().get("roomType"));//0 普通模式 1 俱乐部模式
			ri.setGameType(myRoom.getGametype());//0 牛牛 1 扎金花
			ri.setCreateTime(new Date());
			ri.setBeiyong(myRoom.getIsUp());
			ri.setWinNumber(ub.getWinNumber());//赢的钱
			ri.setClubid(myRoom.getRoomType().get("clubid"));
			ri.insert();
		}

	}


	public int[] getmoneys(int points,int type){




		return null;
	}





}
